package cn.pugle.oj.leetcode;

import cn.pugle.oj.catalog.Backtracking;
import cn.pugle.oj.catalog.GraphProblem;
import cn.pugle.oj.catalog.Unknown;

import java.util.Arrays;

/**
 * https://leetcode.com/problems/surrounded-regions/
 * 错误写法
 *
 * @author tzp
 * @since 2020/11/2
 */
public class LC130 implements Backtracking, GraphProblem {
    int[][] directions = {{-1, 0}, {0, 1}, {1, 0}, {0, -1}};

    public void solve(char[][] board) {
        if (board == null || board.length <= 1) return;
        boolean[][] visited = new boolean[board.length][board[0].length];
        for (int i = 0; i < board.length; i++) {
            for (int j = 0; j < board[0].length; j++) {
                if (board[i][j] == 'O' && !visited[i][j]) {
                    dfs(board, i, j, visited, true);
                }
            }
        }
    }

    //深度优先为O的格子, flood过去所有相连的O, 如果有效flip.
    //记录visited, 不reset, 所以不是回溯
    public void dfs(char[][] board, int i, int j, boolean[][] visited, boolean validIn) {
        boolean valid = validIn;
        visited[i][j] = true;
        for (int k = 0; k < directions.length; k++) {
            int newI = i + directions[k][0];
            int newJ = j + directions[k][1];
            if (!inArea(board, newI, newJ)) {
                valid = false;
            }
        }
        for (int k = 0; k < directions.length; k++) {
            int newI = i + directions[k][0];
            int newJ = j + directions[k][1];
            if (!visited[newI][newJ]) {
                if (inArea(board, newI, newJ)) {
                    dfs(board, newI, newJ, visited, valid);//xxxxxx错误
                }
            }
        }
        if (valid) {
            board[i][j] = 'X';
        }
    }

    public boolean inArea(char[][] board, int i, int j) {
        return i >= 0 && j >= 0 && i < board.length && j < board[0].length;
    }

    public static void main(String[] args) {
        char[][] a = {
                {'X', 'X', 'X', 'X'},
                {'X', 'O', 'O', 'X'},
                {'X', 'X', 'O', 'X'},
                {'X', 'O', 'X', 'X'}};
        new LC130().solve(a);
        System.out.println(Arrays.deepToString(a));
    }
}
